package cn.texous.web.parsing.book.strategy.search.fiction;

import cn.texous.util.commons.constant.Result;
import cn.texous.util.commons.util.GsonUtils;
import cn.texous.web.parsing.book.common.constants.AnaResultCode;
import cn.texous.web.parsing.book.feign.AnaParsingInfo;
import cn.texous.web.parsing.book.feign.ParsingEngineService;
import cn.texous.web.parsing.book.model.param.Param;
import cn.texous.web.parsing.book.model.parser.AnaRequestInfo;
import cn.texous.web.parsing.book.model.parser.origin.AnaOriginParserBaseInfo;
import cn.texous.web.parsing.book.model.parser.origin.AnaOriginParserRequestInfo;
import cn.texous.web.parsing.book.strategy.search.AnaRequester;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * insert description here
 *
 * @author Showa.L
 * @since 2019/7/26 10:45
 */
@Slf4j
public abstract class AbstractAnaRequester<P extends Param> implements AnaRequester<P> {

    @Resource
    private ParsingEngineService parsingEngineService;

    protected void addHttpCharset(AnaOriginParserRequestInfo originParserRequestInfo,
                                  AnaRequestInfo requestInfo,
                                  AnaOriginParserBaseInfo baseInfo) {
        requestInfo.setInCharset(originParserRequestInfo.getInCharset() == null
                ? baseInfo.getCharset() : originParserRequestInfo.getInCharset());
        requestInfo.setOutCharset(originParserRequestInfo.getOutCharset() == null
                ? baseInfo.getCharset() : originParserRequestInfo.getOutCharset());
    }

    @Override
    public Result<String> execute(AnaParsingInfo info) {
        try {
            long start = System.currentTimeMillis();
            log.info("发起请求：{}, 时间：{}", GsonUtils.toJson(info), start);
            Result<String> result = parsingEngineService.parsing(info).execute().body();
            log.info("结束请求所化时间：{}", System.currentTimeMillis() - start);
            return result;
        } catch (IOException e) {
            log.error("调用解析引擎失败", e);
        }
        return Result.out(AnaResultCode.REMOTE_PARSING_ENGINE_ERROR);
    }


}
